import * as React from 'react';
import produce from 'immer'
import { IComponent, IComponentType } from '../src/interfaces';
import {createInformationFunc} from "../src/utils";
import {Dispatch} from "react";

export const widgets: IComponent[] = [
  /*{
    name: 'Card',
    type: IComponentType.DRAG,
    renderProps: {
      style: { width: 300, height: 100 }
    }
  },
  {
    name: 'Grid',
    type: IComponentType.CUSTOM,
    renderProps: {
      style: { width: 600 },
      size: 3,
      column: 3
    }
  },
  {
    name: 'ITEM',
    type: IComponentType.DROP,
  },
  {
    name: 'Heading',
    type: IComponentType.DRAG,
  },
  {
    name: 'Test',
    type: IComponentType.CUSTOM,
    children: [
      {
        name: 'Card',
        type: IComponentType.DRAG
      },
      {
        name: 'ITEM',
        type: IComponentType.DROP,
        children: []
      },
    ],
    renderProps: {
      style: { width: 300, height: 100 }
    }
  }*/
];

export type Information = {
  path: any[],
  data: IComponent
}

interface IReducerStateParams {
  value: any; field: string; path: string
}
function reducerState(state: IComponent, action: IComponent): IComponent {
  console.log('nextState:after', action)
  return action || state
}

export function useStateReducer() {
  const [state, dispatch] = (React.useReducer as any)(reducerState, [])

  const changeField = ({ value, field, path }: IReducerStateParams) => {
    if (typeof path !== 'string') return
    const __path = path.split('-');
    console.log('nextState:before', { value, field, path }, __path)
    const nextState = produce(state, (draft: IComponent[]) => {
      const func = createInformationFunc(__path as any);
      func(draft, (data: any) => {
        if (data) {
          if(field.indexOf('.') > -1) {
            try {
              const execFunc = new Function('data', 'path', 'val', `data.${field} = val`)
              execFunc(data.renderProps, field, value)
            } catch (e) {
              console.error(`“${field}” 在 renderProps 上找不到，无法赋值，请检查代码！\r\n`, e)
            }
          } else {
            data.renderProps[field] = value
          }
        }

        return data
      })
    });

    dispatch(nextState as any)
  }

  return [state, dispatch, changeField]
}

let informationDefault: Information // = originalState.children[0] as Information;
function reducerInfo(state: Information[], action: any) {
  return action || state
}

export function useInformationReducer<T>(defData: IComponent[]): [T, any] {
  const [information, dispatch] = React.useReducer<any>(reducerInfo, informationDefault || defData)

  return [information as T, dispatch]
}